package gui.batches.command;

import hit.core.HomeInventoryTracker;
import hit.core.Item;

import java.util.Iterator;
import java.util.List;

/**
 * A Command that handles undo/redo for adding Items to the ItemFacade
 * */
public class AddItemsCommand extends Command {
	private List<Item> itemsToAdd;
	
	/**
	 * Initialize the AddItemsCommand with a List of Items to add
	 * @param items the Items to add
	 * */
	public AddItemsCommand(List<Item> itemsToAdd) {
		this.itemsToAdd = itemsToAdd;
	}
	
	/**
	 * Adds the items to the ItemFacade
	 * @return the List of Items affected by execution
	 * */
	@Override
	public List<Item> Execute() {
		HomeInventoryTracker.Instance().GetItemFacade().AddItems(itemsToAdd);
		return itemsToAdd;
	}

	/**
	 * Removes the added items from the ItemFacade
	 * @return the List of Items affected by undo
	 * */
	@Override
	public List<Item> Undo() {
		HomeInventoryTracker.Instance().GetItemFacade().UndoAddItems(itemsToAdd);
		
		//if that removed the product from the productcontainer, remove it
		int count = 0;
		Iterator<Item> i = HomeInventoryTracker.Instance().GetItemFacade().GetItemsByProduct(
				itemsToAdd.get(0).GetContainer(), itemsToAdd.get(0).GetProduct());
		while (i.hasNext()) {
			i.next();
			count++;
		}
		if (count == 0) {
			HomeInventoryTracker.Instance().GetProductFacade().RemoveProductFromContainer(
					itemsToAdd.get(0).GetProduct(), itemsToAdd.get(0).GetContainer());
		}
		
		//if that removed the product from the whole system, remove it there too!
		count = 0;
		i = HomeInventoryTracker.Instance().GetItemFacade().GetItemsByProduct(
				null, itemsToAdd.get(0).GetProduct());
		while (i.hasNext()) {
			i.next();
			count++;
		}
		if (count == 0) {
			HomeInventoryTracker.Instance().GetProductFacade().RemoveProduct(
					itemsToAdd.get(0).GetProduct());
		}

		return itemsToAdd;
	}

}
